//
//  HJUserAccountViewModel.swift
//  HJWeiBo
//
//  Created by 夏航军 on 16/9/25.
//  Copyright © 2016年 夏航军. All rights reserved.
//

import UIKit

//路径
//一般归档在沙盒的Document
//拼接文件名的方法String 没有 需要将 String 转换为 NSStirng
//使用默认 as 转换的前提是 被转换的对象不是可选类型

let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("account.plist")


class HJUserAccountViewModel: NSObject {
 
    //获取用户头像的图片
    var iconURL: URL?
    
    //定义一个模型
    var userAccount: HJUserAccount? {
        didSet {
            //一旦外界给userAccount 赋值的时候就立即给iconURL 赋值,就能够确保iconURL一定有值
            let urlString = userAccount?.avatar_large ?? ""
            iconURL = URL(string: urlString)
        }

    }

    
    //创建单例
    static let sharedAccountViewModel: HJUserAccountViewModel = HJUserAccountViewModel()
    

     //判断用户是否登录
    var userLogin: Bool {
        if userAccount?.access_token != nil && isExpires == false {
            return true
        }
        //默认用户是未登录
        return false
    }
    
    //判断用户token是否过期
    var isExpires: Bool {
        if userAccount?.expires_date?.compare(Date()) == ComparisonResult.orderedDescending {
            //没有过期
            return false
        }
        //默认过期
        return true

    }
    
    override init() {
        super.init()

        //从沙盒中取出数据
        self.userAccount = loadUserAccount()
        let urlString = userAccount?.avatar_large ?? ""
        iconURL = URL(string: urlString)
        
    }

    
    internal func loadAccessToken(code: String , finished: @escaping (Bool) -> ()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //请求参数
        let parameters = ["client_id" : client_id,
                          "client_secret" : client_secret,
                          "grant_type" : "authorization_code",
                          "code" : code,
                          "redirect_uri" : redirect_uri
        ]
        
        //利用网络请求POST
        HMNetworkTools.sharedTools.request(method: .POST, urlString: urlString, parameters: parameters) { (responseObject, error) in
            
            if error != nil {
                finished(false)
                return
            }
            
             print(responseObject)
            
            //请求用户信息 实际上就是在一个网络请求的回调中 发起另外一个网络请求
            self.loadUserInfo(dict: responseObject as! [String : Any], finished: finished)
        }

    }
    
    
    
    private func loadUserInfo(dict: [String : Any] , finished: @escaping (Bool) -> ()) {

        let urlString = "https://api.weibo.com/2/users/show.json"
        let access_token = dict["access_token"]!
        let uid = dict["uid"]!

       // print("========================================")
       // print(access_token)
        //请求参数
        let paramters = ["access_token" : access_token,
                         "uid" : uid]
        
        HMNetworkTools.sharedTools.request(method: .GET, urlString: urlString, parameters: paramters) { (responseObject, error) in
            
            if error != nil {
                finished(false)
                return
            }
            
           // print(responseObject)
            //获取用户信息 将字典类型的用户信息 转换成模型数据 -> 将模型数据存储在本地(归档)
            //把这个get请求获取到的数据和上次post请求获取到的数据进行合并
            var userInfoDict = responseObject as! [String:Any]
            
            for keyValues in dict {
                userInfoDict[keyValues.key] = keyValues.value

            }
            
            //字典转模型(给userAccount赋值)
           let  userAccount = HJUserAccount(dict:userInfoDict)
            
           //print(userAccount)
            
            //用用户模型数据存储在本地 方便以后使用
            self.saveUserAccount(userAccount: userAccount)
            
             self.userAccount = userAccount
            
            finished(true)

        }
    }
    
    //通过归档的方式来存数据
    private func saveUserAccount(userAccount: HJUserAccount) {
        
        NSKeyedArchiver.archiveRootObject(userAccount, toFile: path)
    }
    
    private func loadUserAccount() -> HJUserAccount? {
        let userAccount = NSKeyedUnarchiver.unarchiveObject(withFile: path) as? HJUserAccount
        
        return userAccount
    }
}














